//
//  DMHomeViewModel.swift
//  DM_新浪微博
//
//  Created by Damon.JiAo on 16/3/1.
//  Copyright © 2016年 Demon_JiAo. All rights reserved.
//

import UIKit
import AFNetworking

class DMHomeViewModel: NSObject {
    
    lazy var array:[DMHomeViewCellModel] = [DMHomeViewCellModel]()
    
    /** 网络加载数据 */
    func loadData(since_id:Int,max_id:Int,finished:(count:Int)->()){
        
        let afn = AFHTTPSessionManager()
        
        let paramets = ["access_token":DMUserViewModel.shareInstance.model?.access_token ?? ""]
        
        afn.GET("https://api.weibo.com/2/statuses/home_timeline.json", parameters:paramets , progress: nil, success: { (_, JSON) -> Void in
            
            if let json = JSON as? [String:NSObject]{
                
                if let statues = json["statuses"] as?[[String:NSObject]]{
                    // 定义一个临时的数组
                    var temp = [DMHomeViewCellModel]()
                    // 对数组进行便利
                    for statue in statues {
                        
                        let statusModel = DMStatusModel(dic: statue)
                        
                        //添加到数组里
                        let viewModel = DMHomeViewCellModel()
                        viewModel.cellModel = statusModel
//                        self.array.append(viewModel)
                        temp.append(viewModel)
                        
                        // 刷新UI
//                        self.tableView.reloadData()
                    }
                    if max_id > 0{
                        self.array = self.array + temp
                    }else{
                        self.array = temp + self.array
                    }
                    
                    finished(count: temp.count)
                }
                
            }
            
            }) { (_, ERROR) -> Void in
                
                print(ERROR)
        }
        
    }
    
    
    
}
